<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Home</title>
    <script th:src="@{sockjs.js}"></script>
    <script th:src="@{stomp.js}"></script>
    <script th:src="@{jquery-3.2.1.js}"></script>
</head>
<body>
<p>聊天室</p>
<form id="wiselyForm">
    <textarea rows="4" cols="60" name="text"></textarea>
    <input type="submit" />
</form>

<script th:inline="javascript">
    $('#wiselyForm').submit(function (e) {
        e.preventDefault();
        var text = $('#wiselyForm').find('textarea[name="text"]').val();
        sendSplite(text);
    });

    var sock = new SockJS("/endpointChat");     //1 连接endpoint 名称为 /endpointChat
    var stomp = Stomp.over(sock);
    stomp.connect('guest','guest',function (frame) {
        stomp.subscribe("/user/queue/notifications",handleNotification) //2 订阅/user/queue/notification 发送的消息, 这里与控制器的messagingTemplate.
        //converAndSentToUser 中定义的订阅地址保持一致, 这里多了一个/User,并且这个/user 是必须的,使用了/user 才会发送消息到指定的用户;
    });

    function handleNotification(message) {
        $('#output').append("<b>Received:" + message.body + "</b><br/>");
    }

    function sendSplite(text) {
        stomp.send('/chat', {}, text);      //3
    }

    $('#stop').click(function () {
        sock.close();
    });
</script>

<div id="output"></div>

</body>
</html>